package com.highstockings.utils;

import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author:HuangSu(jy01888362@sina.com)
 * @Date:2017/8/29
 * @ProjectName:ClubJazy
 * @Description:图片处理工具类
 */
@Component
public class ImageUtil {

    static int BLOG_PICTURE_WIDTH = 630;        //博客文章固定宽度
    static int BLOG_PICTURE_HEIGTH = 945;       //博客文章固定高度
    static int BLOG_PICTURE_WIDTH_PERCENT = 0;  //博客文章固定宽度比
    static int BLOG_PICTURE_HEIGTH_PERCENT = 0;  //博客文章固定高度比
    // 地址
    static String URL = "http://out58zyl9.bkt.clouddn.com";
    // 编码
    static String ECODING = "UTF-8";
    // 获取img标签正则
    static String IMGURL_REG = "<img.*src=(.*?)[^>]*?>";
    // 获取src路径的正则
    static String IMGSRC_REG = "http:\"?(.*?)(\"|>|\\s+)";

    public static String[] getkeyList(List<String> arrayList, String oldValue, String newValue) {
        String[] result = new String[arrayList.size()];
        for (int i = 0; i < arrayList.size(); i++) {
            result[i] = arrayList.get(i).replace(oldValue, newValue);
        }
        return result;
    }
     /***
     * 1.获取ImageUrl地址
     * @param HTML
     * @return
     */
    public static List<String> getImageUrl(String HTML) {
        Matcher matcher = Pattern.compile(IMGURL_REG).matcher(HTML);
        List<String> listImgUrl = new ArrayList<String>();
        while (matcher.find()) {
            listImgUrl.add(matcher.group());
        }
        return listImgUrl;
    }

    /**
     * 2.获取图片ImageSrc地址
     * @param listImageUrl
     * @return
     */
    public static List<String> getImageSrc(List<String> listImageUrl) {
        List<String> listImgSrc = new ArrayList<String>();
        for (String image : listImageUrl) {
            Matcher matcher = Pattern.compile(IMGSRC_REG).matcher(image);
            while (matcher.find()) {
                if (matcher.group().startsWith(URL)) {
                    listImgSrc.add(matcher.group().substring(0, matcher.group().length() - 1));
                }
            }
        }
        return listImgSrc;
    }

    /**
     * 获取图片尺寸信息
     *
     * @param filePath
     *            a {@link String} object.
     * @return [width, height]
     */
    public static int[] getSizeInfo(String filePath) throws Exception {
        File file = new File(filePath);
        return getSizeInfo(file);
    }

    /**
     * 获取图片尺寸信息
     *
     * @param url
     *            a {@link java.net.URL} object.
     * @return [width,height]
     */
    public static int[] getSizeInfo(URL url) throws Exception {
        InputStream input = null;
        try {
            input = url.openStream();
            return getSizeInfo(input);
        } catch (IOException e) {
            e.printStackTrace();
            throw new Exception(e);
        } finally {
            IOUtils.closeQuietly(input);
        }
    }

    /**
     * 获取图片尺寸信息
     *
     * @param file
     *            a {@link File} object.
     * @return [width,height]
     */
    public static int[] getSizeInfo(File file) throws Exception {
        if (!file.exists()) {
            throw new Exception("file " + file.getAbsolutePath() + " doesn't exist.");
        }
        BufferedInputStream input = null;
        try {
            input = new BufferedInputStream(new FileInputStream(file));
            return getSizeInfo(input);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            throw new Exception(e);
        } finally {
            IOUtils.closeQuietly(input);
        }
    }

    /**
     * 获取图片尺寸
     *
     * @param input
     *            a {@link InputStream} object.
     * @return [width,height]
     */
    public static int[] getSizeInfo(InputStream input) throws Exception {
        try {
            BufferedImage img = ImageIO.read(input);
            int w = img.getWidth(null);
            int h = img.getHeight(null);
            return new int[] { w, h };
        } catch (IOException e) {
            e.printStackTrace();
            throw new Exception(e);
        }
    }

    /**
     * 根据博客缩放图片大小
     * @param fromPic
     * @param toPic
     * @throws IOException
     */
    public static void zoomBySize(File fromPic, File toPic) throws Exception {
        int[] pic_size = getSizeInfo(fromPic);
        if (pic_size[0] > pic_size[1]) {                                //宽大于高
            Thumbnails.of(fromPic).size( BLOG_PICTURE_HEIGTH,BLOG_PICTURE_WIDTH).keepAspectRatio(false).toFile(toPic);
        } else {
            Thumbnails.of(fromPic).size(BLOG_PICTURE_WIDTH, BLOG_PICTURE_HEIGTH).keepAspectRatio(false).toFile(toPic);
        }

    }

    public static void zoomBySize(File fromPic, File toPic, int height, int weight) throws Exception {
        int[] pic_size = getSizeInfo(fromPic);
        if (pic_size[0] > pic_size[1]) {                                //宽大于高
            Thumbnails.of(fromPic).size(height, weight).keepAspectRatio(false).toFile(toPic);
        } else {
            Thumbnails.of(fromPic).size(weight, height).keepAspectRatio(false).toFile(toPic);
        }

    }

    /**
     * 图片放大
     * @param fromPic
     * @param toPic
     * @return
     */
    public static void zoomPicture(File fromPic, File toPic,float percent) throws IOException {
        Thumbnails.of(fromPic).scale(percent).toFile(toPic);//按比例缩小
        //Thumbnails.of(fromPic).scale(2f);//按比例放大
    }

    /**
     * 压缩图片大小
     * @param fromPic
     * @param toPic
     * @param percent
     * @return
     */
    public static void compressPicture(File fromPic, File toPic,int percent) throws IOException {
        //图片尺寸不变，压缩图片文件大小outputQuality实现,参数1为最高质量
        Thumbnails.of(fromPic).scale(1).outputQuality(percent).toFile(toPic);
    }

    /**
     * 更改图片格式
     * @param fromPic
     * @param toPic
     * @param desformat
     * @return
     */
    public static void changePictureFormat(File fromPic,File toPic,String desformat) throws IOException {
        Thumbnails.of(fromPic).scale(1f).outputFormat(desformat).toFile(toPic);
    }

    /**
     *
     * @param baseWidth:浏览器宽度
     * @param width:图片宽度
     * @param height:图片高度
     * @return
     */
    //根据图片宽和高做出判断，自适应浏览器画面大小   浏览器宽度，浏览器高度，作为基准数据，用他们来测定图片上传时默认的宽高比值
    public static Map<String,Integer> pictureShape(int baseWidth,int width, int height) {
        Map<String, Integer> map = new HashMap<>();
        if (width -height>0) {                           //宽〉高,仅仅适用于span8的情况
            map.put("width", baseWidth / 12 * 8 - 20);
            map.put("height", (int) ((baseWidth / 12 * 8 - 20) / 1.8));
        } else if (width -height <0) {
            map.put("width", baseWidth / 12 * 8 - 20);
            map.put("height",  (int)((baseWidth / 12 * 8 - 20) * 1.8));
        } else if (width -height ==0) {
            map.put("width",baseWidth / 12 * 8 - 20);
            map.put("height",baseWidth / 12 * 8 - 20);
        }
        return map;
    }

    /***
     * 3.下载图片
     *
     * @param listImgSrc
     */
    private void Download(List<String> listImgSrc) {
        try {
            for (String url : listImgSrc) {
                String imageName = url.substring(url.lastIndexOf("/") + 1, url.length());
                URL uri = new URL(url);
                InputStream in = uri.openStream();
                FileOutputStream fo = new FileOutputStream(new File(imageName));
                byte[] buf = new byte[1024];
                int length = 0;
                System.out.println("开始下载:" + url);
                while ((length = in.read(buf, 0, buf.length)) != -1) {
                    fo.write(buf, 0, length);
                }
                in.close();
                fo.close();
                System.out.println(imageName + "下载完成");
            }
        } catch (Exception e) {
            System.out.println("下载失败");
        }
    }
}
